#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
'''
结构体及结构体嵌套
'''


from ctypes import *
import platform


class Rect(Structure):
	_fields_ = [
		("index", c_int), # 数据类型要和C中严格对应，否则结果会随机
		("info", c_char * 20) # 20在此对应C中数组大小，似乎比数组大也可工作
	]


class RectNest(Structure):
	_fields_ = [
		("rect_c", Rect),
		# ("nest", c_float)
		("nest", c_int)
	]


if __name__ == '__main__':
	# 普通结构体
	if platform.system() == 'Windows':
		lib_ext = '.dll'
	elif platform.system() == 'Linux':
		lib_ext = '.so'
	elif platform.system() == 'Darwin':
		lib_ext = '.dylib'
	libname = './libdemo_dll' + lib_ext
	library = cdll.LoadLibrary(libname)

	library.readRect.argtypes = [Rect]
	library.readRect.restype = c_void_p

	print("rect index 10")
	rect_a = Rect(10, b'hello world')
	library.readRect(rect_a)

	print("rect index 20")
	rect_a.index = 20
	library.readRect(rect_a)

	# 结构体嵌套
	library.readRectRest.argtypes = [RectNest]
	# library.readRectRest.restype = c_int
	library.readRectRest.restype = c_void_p

	rect_b = Rect(13, b'world')
	# rect_nest = RectNest(rect_b, 23.1)
	rect_nest = RectNest(rect_b, 23)
	library.readRectRest(rect_nest) 
